/**
 * Author : cheneyliu.
 * Date   : 2016/9/28.
 * File   : wohome-api.js.
 */

import Vue from 'vue'
import VueResource from 'vue-resource'
import CryptoJS from 'crypto-js'
import store from './vuex/store'
import errorMap from './errorMap'
import vMessage from './components/message'

var proxyTable = 'http://10.10.20.246:7600' //打包
// var proxyTable = 'http://192.168.254.98:7600' //98
// var proxyTable = 'http://47.100.225.218:7600' //正式

var clientId = 'F05D17AF3AE84192A93D478B21BFB5D0'
var headerKey = 'youyou-head-params'
var api = {
  // 授权接口
  oauth: {
    /**
     * 管理员登录
     * loginName (string): 账号 ,
     * password (string): 密码 ,
     * role (string, optional): 管理员角色,0=旅行社账户, 1 = 后台审核, 2 =前端售票
     */
    adminLogin: '/youyou/system/admin/login'
  },
  // 外部接口
  outer: {
    /**
     * 旅行社添加订单
     * arriveTime (string): 到达时间 ,
     * guideName (string): 导游名字 ,
     * inChannel (string): 入园通道 0=东门，1=西门 ,
     * inTime (string): 入园时间 ,
     * isAdjust (string): 是否接受景区入园调整 T=接受 F=不接受 ,
     * orderList (Array[Map«string,string»]): 订单列表 示例：[ {"passengerName":"黄飞飞","papersType":"0","idCard":"350784199502210013","phone":"18695604770","billType":"0"}, {"passengerName":"李飞飞","papersType":"1","idCard":"350784199502220013","phone":"11121221211","billType":"0"} ] ,
     * orderName (string): 订单名称 ,
     * phone (string): 手机号 ,
     * plateNumber (string): 车牌号 ,
     * remark (string, optional): 旅行社申请其他事项
     */
    travelOrderPassengerAdd:'/youyou/admin/travel/order/passenger/add',

    /**
     * 旅行社订单详情
     * orderId (string): 订单ID
     */
    travelOrderDetail:'/youyou/admin/travel/order/get',

    /**
     * 旅行社订单列表
     */
    travelOrderList:'/youyou/admin/travel/order/list',

    /**
     * 旅行社分页订单列表 
     */
    travelOrderPageList: '/youyou/admin/travel/order/page/list',

    /**
     * 旅行社订单撤销
     * orderId (string): 旅行社名称
     */
    travelOrderUndo: '/youyou/admin/travel/order/undo',



    
    //系统-文件
    /**
     * 文件下载
     * filedId (string): 文件ID
     */
    getDownload: '/youyou/file/download',

    /**
     * 上传文件
     */
    getUpload: '/youyou/file/upload',
  }
}
var url = {
  oauth: 'api_oauth/',
  outer: 'api_outer/',
}

Vue.use(VueResource)


/**
 * 获得Oauth参数
 * @param service
 * @returns {string}
 */
function getOauthParam(service) {
  var args = [];
  args.push(clientId);
  args.push('');
  return args.join(';');
}

/**
 * 获得Outer参数
 * @param {String} service
 * @param {String} token
 * @param {String} body
 * @param {String} sec
 * @returns {string}
 */
function getOuterParam(service, token, body, sec) {
  sec = sec ? 'T' : 'F';
  var args = [];
  var ct = typeof(body) === 'string' ? body : JSON.stringify(body);
  var pa = token.accessToken + [clientId, token.accessTokenKey, service, ct, sec]
    .sort().join('').replace(/\t|\r|\n/g, '') + token.accessToken;
  // console.log('service, token, body, sec', service, token, body, sec)
  // console.log('pa, token.accessToken)', pa, token.accessToken)
  var sign = CryptoJS.HmacMD5(pa, token.accessToken).toString().toUpperCase();
  args.push(clientId);
  args.push(token.accessTokenKey);
  args.push(sign);
  // args.push(sec);
  args.push('');
  return args.join(';');
}

/**
 * 获取接口参数
 * @param options {object}
 *  options {
 *    type {string} 接口类型 oauth,inner,outer
 *    service {string} 接口 mapKey loginGet:'wohome.ac.login.get'
 *    ct {object} 请求内容
 *    sec {boolean, ...} 是否加密
 *  }
 *  @param token {object} 令牌
 * @returns {object}
 */
function getApiParam(options, token) {
  var rs = Object.create(null);
  var type = options.type || '';
  var service = options.service || '';
  var token = token || null;
  var ct = options.ct || {};
  var sec = options.sec || false;

  if (typeof url[type] !== 'undefined') {
    rs.url = proxyTable + api[type][service];
  } else {
    console.error('type error, has\'t ' + type + ' api type!');
    return rs;
  }
  if (typeof api[type][service] !== 'undefined') {
    rs.service = api[type][service];
  } else {
    console.error('service error, ' + type + ' has\'t ' + service + ' api service!');
    return rs;
  }
  switch (type) {
    case 'oauth':
      rs.header = getOauthParam(rs.service);
      break;
    case 'outer':
      if (typeof ct !== 'undefined') {
        rs.header = getOuterParam(rs.service, token, ct, sec);
      } else {
        rs.header = '';
      }
      break;
    default:
      break;
  }
  if (rs.header) {
    rs.options = Object.create(null);
    rs.options.headers = Object.create(null);
    rs.options.headers[headerKey] = rs.header;
    rs.options.headers['Accept'] = '*/*';
  }
  // console.log('rs', rs)
  // rs.body = encodeURIComponent(JSON.stringify(ct));
  rs.body = ct
  return rs;
}

/**
 * 获取接口参数
 * @param options {object}
 *  options {
 *    type {string} 接口类型 oauth,inner,outer
 *    service {string} 接口 mapKey loginGet:'wohome.ac.login.get'
 *    ct {object} 请求内容
 *    sec {boolean, ...} 是否加密
 *  }
 * @returns {object}
 */
function apiSource(options) {
  var self = this
  var token = store.state.token
  var ap = getApiParam(options, token)
  return new Promise((resolve, reject) => {
    Vue.http.post(ap.url, ap.body, ap.options).then((res) => {
      if (isSuccess(res.body)) {
        resolve(parseJSON(res.body))
      } else if (/ERR_/.test(res.body)) {
        var errorJson = JSON.parse(res.body.replace('ERR_{', '{'));

        // 判断是否超速，跳转到登录
        if (errorJson.code === '3004') {
          console.log('重新登录')
          let tabs = [{
            link: '/index',
            title: '首页',
            closable: false
          }];
          let tab = {
            link: '/index',
            title: '首页',
            closable: false
          }
          store.state.tabs = tabs;
          store.state.tab = tab;
          sessionStorage.setItem('tab', JSON.stringify(tab));
          sessionStorage.setItem('tabs', JSON.stringify(store.state.tabs));
          sessionStorage.removeItem('wohome-token')
          localStorage.removeItem('wohome-user')
          store.state.token = null
          store.state.user = {}
          localStorage.removeItem('account')
          localStorage.removeItem('password')
          setTimeout(() => {
            vMessage.error('登录超时，请重新登录！')
          }, 500)
          // window.localStorage.removeItem('account')
          // window.localStorage.removeItem('password')
          store.state.router.go('/login')
        }
        if (errorJson.code && errorJson.msg) {
          vMessage.error(errorJson.msg)
        }
        reject(errorJson);
      } else {
        reject(parseJSON(res.body))
      }
    }, (res) => {
      if (res.code && res.msg) {
        vMessage.error(res.msg)
      }
      reject(res)
    })
  })
}

/**
 * 转码字符串到JSON
 * @param data
 * @returns {*}
 */
function parseJSON(data) {
  // console.log(data, 'ssssssssss', data.substr(0, 1));

  // 解决空格变成加号的问题
  data = data.replace(/\+/g, "%20");

  // 判断值是否文字符串 返回
  if (data.substr(0, 1) !== '[' && data.substr(0, 1) !== '{' && data.substr(0, 3) !== 'ERR') {
    return data
  }
  // data = decodeURIComponent(data);
  var rs = null;
  if (typeof data === 'object') {
    return data;
  }
  if (typeof data == 'undefined'
    || (typeof data == 'string' && data == '')
    || data == null) {
    return {
      code: '505',
      msg: '请求错误或服务器错误!'
    };
  }
  if (/ERR_/.test(data)) {
    var tagflex = false
    try {
      var tmpdata = JSON.parse(data)
    } catch (e) {
      tagflex = true
    }
    if (!tagflex) {
      // console.log('tmpdata', tmpdata)
      if (tmpdata instanceof Array) {
        for (let i = 0; i < tmpdata.length; i++) {
          let tmpstr = JSON.stringify(tmpdata[i])
          if (tmpstr.indexOf('ERR_') !== -1 && tmpstr.indexOf('msg') !== -1) {
            rs = JSON.parse((tmpstr.slice(tmpstr.indexOf('ERR_') + 4, tmpstr.indexOf('}') + 1)).replace(/\\/g, ''));
          }
        }
      }
    } else {
      rs = JSON.parse(data.substr(4));
    }
    // 将英文错误映射为中文提示
    // for (let i = 0; i < errorMap.length; i++) {
    //   if (errorMap[i].code == rs.code) {
    //     rs.msg = errorMap[i].msg
    //     break;
    //   }
    // }
  } else {
    let tmpdata = JSON.parse(data)
    rs = JSON.parse(data);
    if (rs.code && rs.msg) {
      // 将英文错误映射为中文提示
      // for (let i = 0; i < errorMap.length; i++) {
      //   if (errorMap[i].code == rs.code) {
      //     rs.msg = errorMap[i].msg
      //     break;
      //   }
      // }
    }
  }
  return rs;
}

/**
 * 判断是否为成功请求
 * @param data
 * @returns {boolean}
 */
function isSuccess(data) {
  var rs = parseJSON(data);
  if (rs instanceof Array) {
    console.log('!!!!!!!!!!!')
    for (let i = 0; i < rs.length; i++) {
      let tmpstr = JSON.stringify(rs[i])
      if (tmpstr.indexOf('ERR_') !== -1 && tmpstr.indexOf('msg') !== -1) {
        return false
      }
    }
    return true
    // 同时出现code,msg说明服务端响应错误
  } else if (rs.code && rs.msg) {
    return false;
  } else {
    return true;
  }
}

export default apiSource

export {
  apiSource,
  parseJSON,
  isSuccess
}
